package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionalEventListener;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    @Value("${sky.task.timeoutTime}")
    private String timeoutTime;
    @Value("${sky.task.deliveryTime}")
    private String deliveryTime;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "0 * * * * ? ")
    @Transactional
    public void processTimeoutOrder() {
        System.out.println("处理支付超时订单");
        // 查询支付超时订单
        List<Orders> ordersList = orderMapper.getTimeoutOrders(Orders.PENDING_PAYMENT, LocalDateTime.now(), timeoutTime);

        ordersList .forEach(orders -> {
            // 订单支付超时，更新订单状态为4
            Orders ordersUpdate = Orders.builder()
                    .id(orders.getId())
                    .status(Orders.CANCELLED)
                    .cancelReason("订单支付超时，自动取消")
                    .cancelTime(LocalDateTime.now())
                    .build();
            orderMapper.update(ordersUpdate);
        });
    }

    @Scheduled(cron = "0 0 1 * * ? ")
    @Transactional
    public void processDeliveryOrder() {
        System.out.println("处理派送中订单");
        // 查询派送中订单
        List<Orders> ordersList = orderMapper.getTimeoutOrders(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now(), deliveryTime);

        ordersList .forEach(orders -> {
            // 订单派送完成，更新订单状态为5
            Orders ordersUpdate = Orders.builder()
                    .id(orders.getId())
                    .status(Orders.COMPLETED)
                    .build();
            orderMapper.update(ordersUpdate);
        });
    }
}
